package com.xiu.realm;


import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import com.xiu.pojo.ExamUser;
import com.xiu.service.LoginService;

public  class MyRealm extends AuthorizingRealm {
	
	@Autowired
	LoginService loginService;
	

	/**
	 * 授权，对用户进行授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principal) {
		String number = String.valueOf(principal.getPrimaryPrincipal());//将学号/工号 收集
		int examNumber = Integer.parseInt(number);	//将string类型强转成int类型
		SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();//创建一个新的SimpleAuthorizationInfo
		ExamUser examUser = loginService.findRoles(examNumber);//通过 学号/工号 查询该用户角色
	    String role = examUser.getExamRoleName();	//将查出来的角色赋予role
	    System.out.println(role+"=========");
		simpleAuthorizationInfo.addRole(role);		//将角色放进SimpleAuthorizationInfo
		return simpleAuthorizationInfo;				//返回一条SimpleAuthorizationInfo（role）
	}

	
	/**
	 * 对用户进行校验
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenti) throws AuthenticationException {
		String number = (String) authenti.getPrincipal();
		int examNumber = Integer.parseInt(number);
		ExamUser examUser = loginService.findRoles(examNumber);
		AuthenticationInfo authenticationInfo = null;
		if(examUser != null){
			if(examUser.getExamNumber() != null && examUser.getExamPassword() != null){
				authenticationInfo = new SimpleAuthenticationInfo(examUser.getExamNumber(),examUser.getExamPassword(),"myRealm");
			}
		}
		return authenticationInfo;
	}


	
	
}
